<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>星级评分</title>
		<style type="text/css">
			*{margin: 0; padding: 0;}
			li{list-style: none;}
			#list{width: 800px; margin: 100px auto;}
			#box{width: 800px; margin: 300px auto;}
			.star{width: 50px; font-size: 30px; float: left; height: 35px; background: url(img/star.png) no-repeat; cursor: pointer;}
		</style>
		<script type="text/javascript">
			window.onload=function(){
				var t1=new rating();
				t1.init('box',{
					iNow:5,
					num:10
				});
			}
			function rating()
			{
				this.settings={
					num:6,
					iNow:1,
					rate:'',
					color:'red'
				};
				this.index=0;
			}
			rating.prototype.init=function(id,opt)
			{
				extend(this.settings,opt);
				this.index=this.settings.iNow;
				this.obj=document.getElementById(id);
				this.creat();
				this.adiv=this.obj.getElementsByTagName('div');
				var This=this;
				star(this.settings.iNow);
				bindEvent(this.obj,'mouseover',function(ev){
					var ev=ev||event;
					var target=ev.target;
					star(target.index+1);
				});
				bindEvent(this.obj,'click',function(ev){
					var ev=ev||event;
					var target=ev.target;
					This.index=target.index+1;
				});
				bindEvent(this.obj,'mouseout',function(ev){
					star(This.index);
				});
				function star(num)
				{
					var num=parseInt(num);
					for(var i=0;i<This.adiv.length;i++)
					{
						if(num>i)
						{
							if(This.settings.rate=='')
							{
								This.adiv[i].style.backgroundPosition='0 -40px';
							}else
							{
								This.adiv[i].style.background='0';
								This.adiv[i].style.color=This.settings.color;
							}
						}else
						{
							if(This.settings.rate=='')
							{
								This.adiv[i].style.backgroundPosition='0 0';
							}else
							{
								This.adiv[i].style.background='0';
								This.adiv[i].style.color='#ccc';
							}
						}
					}
				}
			}
			rating.prototype.creat=function()
			{
				for(var i=0;i<this.settings.num;i++)
				{
					var div=document.createElement('div');
					div.className="star";
					div.innerHTML=this.settings.rate;
					div.index=i;
					this.obj.appendChild(div);
				}
			}
			function extend(obj1,obj2)
			{
				for(var attr in obj2)
				{
					obj1[attr]=obj2[attr];
				}
			}
			function bindEvent(obj,events,fn)  //绑定事件
			{
				//obj 		楼层
				//events	书架
				//fn		一本书
				obj.listeners=obj.listeners||{};
				obj.listeners[events]=obj.listeners[events]||[];
				obj.listeners[events].push(fn);
				if(obj.addEventListener)
				{
					obj.addEventListener(events,fn,false);
				}else
				{
					obj.attachEvent('on'+events,fn);
				}
			}
			function fireEvent(obj,events) //主动触发自定义事件
			{
				for(var i=0;i<obj.listeners[events].length;i++)
				{
					obj.listeners[events][i]();
				}
			}
		</script>
	</head>
	<body>
		<div id="box">
			
		</div>
	</body>
</html>
